import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image } from '@tarojs/components';
import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import digitWallet from '@/orderSubPack/images/checkstand/digitWallet.png';
import wechat from '@/orderSubPack/images/checkstand/wechat.png';
import unSelect from '@/orderSubPack/images/checkstand/unSelect.png';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import ImageOrIcon from '@/components/ImageOrIcon';
import CountDown from '@/components/CountDown';

import '../style.scss';
import './index.scss';
import CodeVerify from '../../verifyCodeInput';

const Index = ({
  dispatch,
  loading,
  totalPrice,
  paymentData = {},
  digitWalletBindSatus = {},
  payActivity = {},
  affirmActivity,
}) => {
  useShowLoading(loading, ['order/toPayByPayType']);

  const [payType, setPayType] = useState(1);
  const [showCodeInput, setShowCodeInput] = useState(false);
  const [finalPrice, setFinalPrice] = useState(-1);
  const urlParms = useRef(null);
  let fromFlag = 0; //0-购物车 1-我的订单列表 2-订单详情
  let theOrderIdList = [];
  let theOrderItemIdList = [];
  let theTotalPrice = 0;

  urlParms.current = getCurrentInstance().router.params;

  if (urlParms.current.orderId) {
    theOrderIdList.push(urlParms.current.orderId);
    let productIdList = urlParms.current.productIds.split('_');
    theOrderItemIdList = [...productIdList];
    theTotalPrice = urlParms.current.totalPrice;
    if (urlParms.current.from == 'order') {
      fromFlag = 1;
    } else if (urlParms.current.from == 'orderDetail') {
      fromFlag = 2;
    }
  }
  if (!fromFlag) {
    const { orderIdList = [], orderItemIdList = [] } = paymentData;
    theOrderIdList = [...orderIdList];
    theOrderItemIdList = [...orderItemIdList];
    theTotalPrice = totalPrice;
  }

  const showToast = (url, message, showCancel = false) => {
    Taro.showModal({
      title: '支付提示',
      content: message,
      showCancel: showCancel,
      cancelText: '返回',
      mask: true,
      success: function (res) {
        if (res.confirm) {
          Taro.redirectTo({ url });
        } else if (res.cancel) {
          utils.backWithRefreash();
        }
      },
    });
  };

  const handleResult = (message = '', status, unShow = false) => {
    let url = '',
      showCancel = false;
    if (fromFlag == 1) {
      url = '/orderSubPack/order-list/index';
    } else if (fromFlag == 2) {
      url =
        '/orderSubPack/orderDetail/index' +
        '?' +
        'orderId=' +
        urlParms.current.orderId +
        '&isNeedRefreshOrderList=true';
    } else {
      url = '/orderSubPack/orderDetail/index' + '?' + 'orderId=' + theOrderIdList[0];
      if (status == 'success') {
        message += '，查看订单';
      }
      showCancel = true;
    }

    if (unShow && message.length === 0) {
      Taro.redirectTo({ url });
    } else {
      showToast(url, message, showCancel);
    }
  };

  const goPage_ABC = (extra) => {
    let url = '/orderSubPack/payByABC/index?url=' + encodeURIComponent(extra);
    if (Taro.$isH5) {
      url = extra;
    }
    Taro.redirectTo({
      url,
    });
  };

  const doPay = async (code = '') => {
    let payTypeName = '';
    switch (payType) {
      case 1:
        payTypeName = 'WXPAY';
        break;
      case 2:
        payTypeName = 'DIGICCY';
        break;
      case 3:
        payTypeName = 'ABCPAY';
        break;
      case 4:
        payTypeName = 'BCMPAY';
        break;
      case 5:
        payTypeName = 'PSBCPAY';
        break;
      default:
        break;
    }
    const data = {
      openId:await Taro.getOpenId(),
      payOrderItemListRequest: theOrderItemIdList.map((v) => ({
        productOrderLineItemId: v,
      })),
      payOrderListRequest: theOrderIdList.map((v) => ({ purchaseOrderId: v })),
      payType: payTypeName,
      totalPrice: parseFloat(finalPrice) >= 0 ? finalPrice : theTotalPrice,
    };
    if (code.length == 6 && payType == 2) {
      data.code = code;
    }

    dispatch({
      type: 'order/toPayByPayType',
      payload: data,
    })
      .then((res) => {
        if (parseFloat(theTotalPrice) === 0) {
          return handleResult(res.message || '', '', true);
        }
        if (res.message) {
          return handleResult(res.message, 'error');
        }
        if (payType == 2) {
          return handleResult('支付已完成', 'success');
        }
        if (!res.payResult && parseFloat(theTotalPrice) === 0) {
          return handleResult('支付已完成', 'success');
        }
        const payResult = JSON.parse(res.payResult);
        if (payType == 3 || payType == 4 || payType == 5) {
          return goPage_ABC(payResult.extra);
        }
        const extra = JSON.parse(payResult.extra);
        if (Taro.$isH5) {
          utils.WXPayByH5(extra, handleResult, handleResult, handleResult);
        } else {
          Taro.requestPayment({
            ...extra,
            success: function () {
              handleResult('支付已完成', 'success');
            },
            fail: function (rlt) {
              if (rlt.errMsg && rlt.errMsg == 'requestPayment:fail cancel') {
                handleResult('支付取消', 'error');
              } else {
                handleResult('支付失败', 'error');
              }
            },
          });
        }
      })
      .catch(() => {
        handleResult('订单失效', 'error');
      });
  };
  const checkWalletBindStatus = () => {
    dispatch({
      type: 'otherApi/checkWalletBindStatus',
      payload: { forNext: false },
    });
  };
  const handleDigitWallet = () => {
    setShowCodeInput(true);
  };
  const handlePay = debounce(() => {
    if (payType == 1) {
      doPay();
    } else if (payType == 2) {
      handleDigitWallet();
    } else if (payType == 3 || payType == 4 || payType == 5) {
      //农业银行、交通银行、邮政储蓄银行
      doPay();
    }
  }, 2000);

  const closeCodeInput = () => {
    setShowCodeInput(false);
  };

  const getPayActivity = () => {
    dispatch({
      type: 'order/selectActivityAmount',
      payload: {
        orderId: theOrderIdList[0],
        payType,
        bizScene: '1',
      },
    });
  };

  useDidShow(() => {
    // if (payType == 3) {
    //   //农行H5支付返回，跳到订单详情页
    //   let url = '/orderSubPack/orderDetail/index' + '?' + 'orderId=' + theOrderIdList[0];
    //   Taro.redirectTo({ url });
    //   return;
    // }
  });
  useEffect(() => {
    checkWalletBindStatus();
  }, []);
  useEffect(() => {
    theOrderIdList?.length > 0 && getPayActivity();
  }, [payType]);
  useEffect(() => {
    if (Object.keys(payActivity).length > 0) {
      setFinalPrice(payActivity.afterDiscountAmount ?? theTotalPrice);
    }
  }, [payActivity]);
  useEffect(() => {
    if (!theOrderIdList || theOrderIdList.length === 0) {
      Taro.showToast({
        mask: true,
        title: '订单失效',
        icon: 'none',
        duration: 2000,
      });
      setTimeout(() => {
        Taro.redirectTo({
          url: '/pages/mainPages/cartSin/index',
        });
      }, 2000);
    }
  }, [theOrderIdList]);
  useEffect(() => {
    if (parseFloat(theTotalPrice) == 0 && openId) {
      doPay();
    }
  }, [openId]);

  // 获取每家银行支付的优惠活动
  // useEffect(() => {
  //   dispatch({
  //     type: 'order/getAffirmActivity',
  //   });
  // }, []);

  return (
    <View className="checkstand-affirm affirm-style">
      {parseFloat(theTotalPrice) > 0 && (
        <>
          <DefaultNavBar
            title="收银台"
            onBackClick={() => {
              utils.backWithRefreash();
            }}
          />
          <CodeVerify
            isOpened={showCodeInput}
            handleClose={closeCodeInput}
            handleDigitWalletPay={doPay}
          />
          <View className="affirmContent">
            <View className="head">
              <View className="order-price">
                <View className="pirce">¥{parseFloat(theTotalPrice).toFixed(2)}</View>
                <View className="cutdown">
                  支付倒计时：
                  <CountDown
                    className="cutdown-content"
                    format={{ hours: ':', minutes: ':', seconds: '' }}
                    initTimes={600}
                  />
                </View>
              </View>
              <View className="payType-text">请选择支付方式</View>
            </View>
            <View className="content">
              <View className="pay-lists">
                <View className="pay-item show">
                  <Image className="pay-icon" src={wechat} />

                  <View>
                    <View>微信支付</View>

                    {!affirmActivity?.wechat ? null : (
                      <View className="activity customePageBorderStyle">
                        <View className="txt customePageStyle omit-1">
                          {affirmActivity?.wechat}
                        </View>
                      </View>
                    )}
                  </View>

                  <View className="right">
                    {payType == 1 && parseFloat(payActivity.preferentialAmount) > 0 && (
                      <Text className="redInfo">立减-{payActivity.preferentialAmount}</Text>
                    )}
                    <View className="check-box" onClick={() => setPayType(1)}>
                      <ImageOrIcon
                        {...{
                          className: 'checkIcon',
                          name: payType == 1 && 'icon_chose',
                          size: 40,
                          src: unSelect,
                        }}
                      />
                    </View>
                  </View>
                </View>
                {/* <View
                  className={[
                    'pay-item',
                    digitWalletBindSatus.digitalWalletId?.length > 0 &&
                      digitWalletBindSatus.digitalPayFlag &&
                      'show',
                  ].join(' ')}
                >
                  <Image className="pay-icon" src={digitWallet} />
                  <View>
                    <View>中行数字人民币支付</View>

                    {!affirmActivity?.bc ? null : (
                      <View className="activity customePageBorderStyle">
                        <View className="txt customePageStyle omit-1">{affirmActivity?.bc}</View>
                      </View>
                    )}
                  </View>
                  <View className="right">
                    {payType == 2 && parseFloat(payActivity.preferentialAmount) > 0 && (
                      <Text className="redInfo">立减-{payActivity.preferentialAmount}</Text>
                    )}
                    <View className="check-box" onClick={() => setPayType(2)}>
                      <ImageOrIcon
                        {...{
                          className: 'checkIcon',
                          name: payType == 2 && 'icon_chose',
                          size: 40,
                          src: unSelect,
                        }}
                      />
                    </View>
                  </View>
                </View> */}
                {/* <View className={['pay-item', 'show'].join(' ')}>
                  <Image className="pay-icon" src={digitWallet} />
                  <View>
                    <View>农行数字人民币支付</View>

                    {!affirmActivity?.abc ? null : (
                      <View className="activity customePageBorderStyle">
                        <View className="txt customePageStyle omit-1">{affirmActivity?.abc}</View>
                      </View>
                    )}
                  </View>

                  <View className="right">
                    {payType == 3 && parseFloat(payActivity.preferentialAmount) > 0 && (
                      <Text className="redInfo">立减-{payActivity.preferentialAmount}</Text>
                    )}
                    <View className="check-box" onClick={() => setPayType(3)}>
                      <ImageOrIcon
                        {...{
                          className: 'checkIcon',
                          name: payType == 3 && 'icon_chose',
                          size: 40,
                          src: unSelect,
                        }}
                      />
                    </View>
                  </View>
                </View> */}
                {/* <View className={['pay-item', 'show'].join(' ')}>
                  <Image className="pay-icon" src={digitWallet} />

                  <View>
                    <View>交行数字人民币支付</View>

                    {!affirmActivity?.bcm ? null : (
                      <View className="activity customePageBorderStyle">
                        <View className="txt customePageStyle omit-1">{affirmActivity?.bcm}</View>
                      </View>
                    )}
                  </View>

                  <View className="right">
                    {payType == 4 && parseFloat(payActivity.preferentialAmount) > 0 && (
                      <Text className="redInfo">立减-{payActivity.preferentialAmount}</Text>
                    )}
                    <View className="check-box" onClick={() => setPayType(4)}>
                      <ImageOrIcon
                        {...{
                          className: 'checkIcon',
                          name: payType == 4 && 'icon_chose',
                          size: 40,
                          src: unSelect,
                        }}
                      />
                    </View>
                  </View>
                </View> */}
                {/* <View className={['pay-item', 'show'].join(' ')}>
                  <Image className="pay-icon" src={digitWallet} />

                  <View>
                    <View>邮储数字人民币支付</View>

                    {!affirmActivity?.psbc ? null : (
                      <View className="activity customePageBorderStyle">
                        <View className="txt customePageStyle omit-1">{affirmActivity?.psbc}</View>
                      </View>
                    )}
                  </View>

                  <View className="right">
                    {payType == 5 && parseFloat(payActivity.preferentialAmount) > 0 && (
                      <Text className="redInfo">立减-{payActivity.preferentialAmount}</Text>
                    )}
                    <View className="check-box" onClick={() => setPayType(5)}>
                      <ImageOrIcon
                        {...{
                          className: 'checkIcon',
                          name: payType == 5 && 'icon_chose',
                          size: 40,
                          src: unSelect,
                        }}
                      />
                    </View>
                  </View>
                </View> */}
              </View>
              <View className="btn-view-card confirmPay">
                <View
                  className={
                    'btn-blue theColor customePageBackgroundStyle' +
                    (parseFloat(finalPrice) >= 0 ? '' : 'disable')
                  }
                  onClick={handlePay}
                >
                  <Text>确认支付 ¥{parseFloat(finalPrice) >= 0 ? finalPrice : theTotalPrice}</Text>
                  <Text
                    className={
                      'secondLine ' +
                      (parseFloat(payActivity.preferentialAmount) > 0 ? 'enable' : '')
                    }
                  >
                    （已优惠{parseFloat(payActivity.preferentialAmount)}元）
                  </Text>
                </View>
              </View>
            </View>
          </View>
        </>
      )}
    </View>
  );
};
export default connect(({ loading, order, login, otherApi }) => {
  const { cartOrderCache } = order;
  return {
    loading,
    paymentData: cartOrderCache.paymentData,
    totalPrice: cartOrderCache.totalPrice,
    digitWalletBindSatus: otherApi.digitWalletBindSatus,
    payActivity: order.payActivity,
    affirmActivity: order.affirmActivity,
  };
})(Index);
